# 朴素贝叶斯分类算法

import pandas as pd
import numpy as np
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score

df = pd.read_excel("D:\\A_TXT文件\\sheet.xlsx", sheet_name="Sheet1")
df_encoded = pd.get_dummies(df, columns=['age', 'income', 'students', 'credit'])
X = df_encoded.drop('buy', axis=1)
y = df_encoded['buy']

mnb = MultinomialNB(alpha=1.0e-10, fit_prior=True, class_prior=None)
mnb.fit(X,y)

#类先验概率=各类的个数/类的总个数
print("类先验概率:",np.exp(mnb.class_log_prior_))
print("每个标签类别下包含的样本数:", mnb.class_count_)
y_hat=mnb.predict(X)
print('训练准确率:',accuracy_score(y,y_hat))
print("预测的分类:",mnb.predict(X))